#define DEBUG
#include <cstdio>

using namespace std;

const int maxn=200000, maxm=100000, inf=0x7fffffff;

class Graph {
public:
  int n, m, ind[maxn+1], to[4*maxn+1], val[4*maxn+1], link[4*maxn+1];

  void addSide(int u, int v, int w) {
    m++;
    to[m] = v;
    val[m] = w;
    link[m] = ind[u];
    ind[u] = m;
  }

  int spfa(int s, int t) {
    static int dis[maxn+1], que[maxn+1], times[maxn+1];
    static bool book[maxn+1];
    for (int i=0; i<=n; i++) {
      dis[i] = inf;
    }
    que[1]=s, book[s]=true, dis[s]=0;

    for (int h=0, t=1, sum=0, len = 1, temp; h!=t; ) {
      h = h % n + 1;
      if (dis[que[h]]<=sum/len+1) {
	int o = que[h];
	times[o]++;
	times[0]++;
	if (times[o]>=n || times[0]>=5000000) {
	  return -1;
	}
	book[o] = false;
	sum -= dis[o];
	len--;
	for (int i=ind[o]; i; i=link[i]) {
	  if (dis[to[i]] > dis[o] + val[i]) {
	    dis[to[i]] = dis[o] + val[i];
	    if (!book[to[i]]) {
	      len++;
	      book[to[i]] = true;
	      t = t % n + 1;
	      que[t] = to[i];
	      sum += dis[to[i]];
	      if (dis[que[h % n + 1]] > dis[que[t]]) {
		temp = que[h % n + 1], que[h % n + 1] = que[t], que[t] = temp;
	      }
	    }
	  }
	}
      } else {
	t = t % n + 1;
	que[t] = que[h];
      }
    }
    return dis[t];
  }
};

int main() {
#ifdef DEBUG
  freopen("3233.in", "r", stdin);
  freopen("3233.out", "w", stdout);
#endif

  static Graph g;
  int n, m;
  scanf("%d %d", &n, &m);
  g.n = n;
  for (int i=1; i<=n; i++) {
    g.addSide(i-1, i, 1);
    g.addSide(i, i-1, 0);
  }
  for (int i=1; i<=m; i++) {
    int l, r;
    scanf("%d %d", &l, &r);
    g.addSide(l-1, r, 1);
    g.addSide(r, l-1, -1);
  }
  printf("%d", g.spfa(0, n));

  fclose(stdin);
  fclose(stdout);
  return 0;
}
